package com.yztstudy.Filter;

import com.yztstudy.Entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //字符过滤
        response.setContentType("text/html;charset=utf-8");

        //1.得到session
        HttpSession session = request.getSession();
        //2.得到用户信息
        User user = (User) session.getAttribute("loginUser");
        //3.判断用户是否登录
        if (user != null)
        {
            return true;
        }else {
            response.getWriter().write("<script>alert('请先登录!'); location.href = '/login';</script>");
            return false;
        }
    }
}
